import json

from django.conf import settings
from django.http import JsonResponse
from fdfs_client.client import Fdfs_client
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework.generics import ListAPIView,RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.goods.models import SPU, Brand, GoodsChannel, GoodsChannelGroup, GoodsCategory, SKUImage
from apps.meiduo_admin.serializers.spu import SPUSerializer, GoodsBrandSimpleSerializer, CategorySerilaizer, \
    TwoCategorySerilaizer
from apps.meiduo_admin.utils.pagination import MeiduoPagination


class SPUsView(ListCreateAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSerializer
    pagination_class = MeiduoPagination
class SPUView(RetrieveUpdateDestroyAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSerializer
    pagination_class = MeiduoPagination

#获取品牌的信息
class GoodsSimpleAPIView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = GoodsBrandSimpleSerializer

#获取一级分类信息
class GoodsChannelCategoriesAPIView(ListAPIView):
    queryset = GoodsCategory.objects.filter(parent__isnull=True)
    serializer_class = CategorySerilaizer
#获取二三级分类
class GoodsChannelsCategoriesAPIView(RetrieveAPIView):
    # queryset = GoodsCategory.objects.filter(parent__isnull=False)
    def get_queryset(self):
        pk = self.kwargs.get('pk')

        return GoodsCategory.objects.filter(id=pk)
    serializer_class = TwoCategorySerilaizer

#上传图片
class ImageView(APIView):
    def post(self,request):
        image = request.data.get('image')
        # 处理 上传图片  创建图片对象
        image_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        data = image_client.upload_by_buffer(image.read())

        image_url = data.get("Remote file_id")
        return Response({
            'img_url':settings.FDFS_BASE_URL+image_url
        },status=201)

